package com.example.rpc.main;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alipay.sofa.rpc.config.ConsumerConfig;
import com.alipay.sofa.rpc.config.RegistryConfig;
import com.alipay.sofa.rpc.context.RpcInvokeContext;
import com.example.rpc.service.HelloService;

import cn.hutool.core.map.MapBuilder;

/**
 * Quick Start client
 */
public class QuickStartClient {
    public static void main(String[] args) {
    	
//    	RoundRobinLoadBalancer
    	
    	RegistryConfig registryConfigZk = new RegistryConfig()
   	         .setProtocol("zookeeper")
   	         .setAddress("127.0.0.1:2181");
    	
    	RegistryConfig registryConfigConsul = new RegistryConfig()
      	         .setProtocol("consul")
      	         .setAddress("127.0.0.1:8500");
    	
    	RegistryConfig registryConfigLocal = new RegistryConfig()
     	         .setProtocol("local")
     	         .setFile("./logs/localRegistry.reg");
    	
    	List<RegistryConfig> registryConfigs = new ArrayList<RegistryConfig>();
//    	registryConfigs.add(registryConfigZk);
//    	registryConfigs.add(registryConfigConsul);
    	registryConfigs.add(registryConfigLocal);
    	
    	//路由 https://www.sofastack.tech/blog/sofa-rpc-routing-implementation/
    	//roundRobin		顺序   
    	//random			权重随机
    	//localPreference	本地优先(LocalPreferenceLoadBalancer)
    	//consistent 	一致性 Hash(ConsistentHashLoadBalancer)

    	
        ConsumerConfig<HelloService> consumerConfig = new ConsumerConfig<HelloService>()
            .setInterfaceId(HelloService.class.getName()) // 指定接口
            .setCheck(false)//是否检查强依赖	无可用服务端启动失败
            .setLoadBalancer("random")// 常用
            .setProtocol("bolt") // 指定协议
            .setRegistry(registryConfigs);
//            .setDirectUrl("bolt://127.0.0.1:12200"); // 指定直连地址
        
        
        // 生成代理类
        int i = 0;
        while (true) {
        	try {
        		//新加透传参数
//        		Map params = MapBuilder.create().put("id", 1).put("name", "sim").build();
        		RpcInvokeContext.getContext().putRequestBaggage("req_bag", i+"-c2c");
        		HelloService helloService = consumerConfig.refer();
        		System.out.println(helloService.sayHello("world --"+(i++)+"; bag:"+RpcInvokeContext.getContext().getRequestBaggage("req_bag")));
        		Thread.sleep(3000);
        	} catch (Exception e) {
        		e.printStackTrace();
        	}
        }
    }
}